package com.yst.shader.ext

import android.content.Context
import android.graphics.Color
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_HOVER_ENTER
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ScrollView
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.commit

/**
 * @author: xuyujian@ysten.com
 *  @date: 2020/8/14 13:36
 */

fun ViewGroup.addBtn(txt: String, click: () -> Unit) = Button(this.context).apply {
    setOnFocusChangeListener { v, hasFocus ->
        if (hasFocus) {
            v.animate().scaleX(1f)
                .scaleY(1f)
                .start()
            v.setBackgroundColor(Color.rgb(66, 66, 66))
        } else {
            v.animate().scaleX(1f)
                .scaleY(1f)
                .alpha(1f)
                .start()
            v.setBackgroundColor(Color.WHITE)
        }
    }
    text = txt
    textSize = 48f
    setOnClickListener {
        click()
    }

    this@addBtn.addView(this)
}

fun ViewGroup.pushFragment(txt: String, fragment: Fragment) =
    addBtn(txt) {
        (context as FragmentActivity).run {
            supportFragmentManager.commit {
                replace(android.R.id.content, fragment)
                addToBackStack(txt)
            }
        }
    }

fun Context.newContainer(init: LinearLayout.() -> Unit): ViewGroup {
    return ScrollView(this).apply {
        addView(LinearLayout(this@newContainer).apply {
            orientation = LinearLayout.VERTICAL
            init()
        }
        )
    }
}


fun ViewGroup.hoverOnFocusInChildren() {
    this.children.forEach {
        it.isFocusable = true
        it.isFocusableInTouchMode = true
        it.setOnHoverListener(HoverListener)
    }
}

object HoverListener : View.OnHoverListener {

    override fun onHover(v: View, event: MotionEvent): Boolean {
        return when (event.action) {
            ACTION_HOVER_ENTER -> {
                v.requestFocus()
                println("hover for request focus v:$v")
                true
            }
            else -> false
        }
    }
}

object FocusListener : View.OnFocusChangeListener {


    var callBack: ((View, Boolean) -> Unit)? = null

    override fun onFocusChange(v: View, hasFocus: Boolean) {
        if (hasFocus) {
            v.animate().scaleX(1.2f).scaleY(1.2f).start()
        } else {
            v.animate().scaleX(1f).scaleY(1f).start()
        }

        callBack?.invoke(v, hasFocus)
    }
}
